const path = require('path');
const fs = require('fs');
const { SyncHook } = require('tapable');
const Compilation = require('./Compilation');
module.exports = class Compiler {
    constructor(options) {
        this.options = options;
        this.hooks = {
            run: new SyncHook(),
            done: new SyncHook(),
        }
    }

    run(callback) {
        // 编译开始前, 通知所有插件的钩子
        this.hooks.run.call();
        const onCompiled = (err, stats, fileDependencies) => {
            const { assets } = stats
            for(const filename in assets) {
                const filePath = path.join(this.options.output.path, filename)
                fs.writeFileSync(filePath, assets[filename], 'utf-8')
            }
            callback(err, {toJson: () => stats})
            console.log(fileDependencies)
            fileDependencies.forEach(filePath => {
                fs.watch(filePath, () => {
                    this.compile(onCompiled)
                })
            })

        }
        // 编译
        this.compile(onCompiled)
    }
    compile(callback) {
        const compilation = new Compilation(this.options, this);
        compilation.build(callback);
    }
}